<?php

namespace app\models;

use yii\base\Exception;
use yii\db\ActiveRecord;

/**
 * 卡账单
 * Class CardBill
 * @package app\models
 *
 * @property integer $id PK
 * @property integer $card_id 卡编号
 * @property integer $start_time 开始时间
 * @property integer $end_time 结束时间
 * @property float $money 金额
 * @property integer $create_time 创建时间
 */
class CardBill extends ActiveRecord
{
    /**
     * 更新账单
     * @param integer $cardId 卡编号
     * @param string $month 月份2018-01
     * @param float $data 数据用量（B）
     * @param integer $sms 短信用量（条）
     * @param integer $voice 语音用量（分钟）
     * @throws Exception
     */
    public static function updateBill($cardId, $month, $data, $sms, $voice)
    {
        $card = Card::findOne(['id' => $cardId]);
        if (empty($card->uid)) {
            return;
        }
        if (empty($card->package_id)) {
            throw new Exception('创建卡账单时发现没有设置套餐。');
        }

        $startTime = strtotime($month . '-01');
        if (CardBill::find()
            ->andWhere(['card_id' => $cardId])
            ->andWhere(['start_time' => $startTime])
            ->exists()) {
            return;
        }

        // 计算账单金额
        $package = $card->package;
        $money = $package->price;
        if (Util::comp($data, $package->data, 4) > 0 && !empty($package->extra_data)) {
            $extraData = $data - $package->data;
            $money += $extraData * $package->extra_data_price / $package->extra_data;
        }
        if ($sms > $package->sms && !empty($package->extra_sms_price)) {
            $money += ($sms - $package->sms) * $package->extra_sms_price;
        }

        if (ceil($voice) > $package->voice && !empty($package->extra_voice_price)) {
            $extraVoice = ceil($voice) - $package->voice;
            $money += $extraVoice * $package->extra_voice_price;
        }

        $bill = new CardBill();
        $bill->card_id = $cardId;
        $bill->start_time = $startTime;
        $bill->end_time = strtotime('+1 month', $startTime) - 1;
        $bill->money = $money;
        $bill->create_time = time();
        $bill->save();
    }
}
